package com.mixed.db;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.mixed.db.dbutil.DbUtilHelper;
import com.mixed.db.model.PageInfo;

public class BaseDao implements Dao {
	
	protected QueryRunner dbQuery = new QueryRunner();
	
	public BaseDao(){
		
	}
	
	public BaseDao(DataSource dataSource) {
		dbQuery = DbUtilHelper.createQueryRunner();
	}

	public int save(final String sql, final Object[] parameters){
		try {
			return dbQuery.update(DbUtilHelper.getConnection(), sql, parameters);
		} catch (SQLException e) {
			throw new MixedDbException(e);
		}
	}

	public int update(final String sql, final Object[] parameters) {
		try {
			return dbQuery.update(DbUtilHelper.getConnection(), sql, parameters);
		} catch (SQLException e) {
			throw new MixedDbException(e);
		}
	}

	public int delete(final String sql, final Integer id) {
		try {
			return dbQuery.update(DbUtilHelper.getConnection(), sql, id);
		} catch (SQLException e) {
			throw new MixedDbException(e);
		}
	}

	public int deleteByCondition(final String sql, final Object[] parameters){
		try {
			return dbQuery.update(DbUtilHelper.getConnection(), sql, parameters);
		} catch (SQLException e) {
			throw new MixedDbException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public Object get(final String sql, final Object clazz, final Object[] parameters){
		try {
			return dbQuery.query(DbUtilHelper.getConnection(), sql, new BeanHandler(clazz.getClass()));
		} catch (SQLException e) {
			throw new MixedDbException(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	public List findPageByCondition(final String sql, final Class clz, final Object[] parameters, final PageInfo pageInfo){
		try {
			return dbQuery.query(DbUtilHelper.getConnection(), sql, new BeanListHandler(clz), parameters);
		} catch (SQLException e) {
			throw new MixedDbException(e);
		}
	}

}
